package wpmp.portal.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.BooleanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import wcommons.httputils.RequestUtils;
import wcommons.httputils.ResponseUtils;
import wcommons.httputils.quickbean.RespInfo;
import wcommons.lang.quickbean.Message;
import wpmp.portal.service.UserService;
import wpmp.security.client.internal.SecurityUtils;

/**
 * @author Wayne.Wang<5waynewang@gmail.com>
 * @since 11:49:12 AM Dec 5, 2013
 */
@Controller
@RequestMapping("/login.do")
public class LoginController extends BaseController {

	@Autowired
	private UserService service;

	@RequestMapping(method = { RequestMethod.GET, RequestMethod.POST })
	public void login(HttpServletRequest req, HttpServletResponse resp,
			@RequestParam(value = "loginName", required = true) String loginName,
			@RequestParam(value = "password", required = true) String password,
			@RequestParam(value = "rememberPassword", required = false) Boolean rememberPassword) throws Exception {
		final String remoteIp = RequestUtils.getRemoteIp(req);

		if (wcommons.lang.StringUtils.isBlank(loginName, password)) {
			log.warn("empty loginName or password from [{}]", remoteIp);
			ResponseUtils.renderJson(resp, Message.getErrorMessageString("请输入用户名和密码"));
			return;
		}

		if (log.isDebugEnabled()) {
			log.debug("[{}] retry to login from [{}]", loginName, remoteIp);
		}

		final RespInfo<wpmp.utils.quickbean.User> respInfo;
		try {
			respInfo = service.login(loginName, password, BooleanUtils.isTrue(rememberPassword) ? 10 : null);
		}
		catch (Exception e) {
			log.error("Error to login by [" + loginName + "] from [" + remoteIp + "]\r\n", e);
			ResponseUtils.renderJson(resp, Message.getErrorMessageString("登录出错，请联系管理员"));
			return;
		}

		if (respInfo == null) {
			ResponseUtils.renderJson(resp, Message.getErrorMessageString("登录失败，请联系管理员"));
			return;
		}

		if (respInfo.getCode() != 200) {
			if (log.isInfoEnabled()) {
				log.info("[{}] is failed to login from [{}], RemoteResponse:[{}]", loginName, remoteIp, respInfo);
			}

			ResponseUtils.renderJson(resp, Message.getErrorMessageString("登录失败，错误的用户名或密码"));
			return;
		}

		final String securityId = respInfo.getResult().getSecurityId();

		if (log.isDebugEnabled()) {
			log.debug("securityId={}", securityId);
		}

		// 清除密钥
		SecurityUtils.clearSecurityId(req, resp);
		// 清除用户名
		SecurityUtils.clearLoginName(req, resp);
		// 如果记住密码，则失效时间默认十天，否则当前会话有效
		if (BooleanUtils.isTrue(rememberPassword)) {
			SecurityUtils.setSecurityIdToCookie(resp, securityId, 10);
			SecurityUtils.setLoginNameToCookie(resp, loginName, 10);
		}
		else {
			SecurityUtils.setSecurityIdToCookie(resp, securityId);
			SecurityUtils.setLoginNameToCookie(resp, loginName);
		}

		if (log.isInfoEnabled()) {
			log.info("[{}] login by password from [{}] successfully", loginName, remoteIp);
		}

		ResponseUtils.renderJson(resp, Message.getDefaultMessageString());
	}
}
